package cn.zftt.common.config;

import cn.zftt.quartz.dao.JobLogDao;
import cn.zftt.quartz.model.JobLog;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobKey;
import org.quartz.JobListener;

import java.util.Date;

/**
 * @author zhangfeng
 */
public class JobLogListener implements JobListener {

    private ThreadLocal<Long> id = new ThreadLocal<>();

    private JobLogDao jobLogDao;

    @Override
    public String getName() {
        return getClass().getSimpleName();
    }

    @Override
    public void jobToBeExecuted(JobExecutionContext context) {
        JobKey key = context.getJobDetail().getKey();
        JobLog jobLog = new JobLog();
        jobLog.setStartTime(context.getFireTime());
        jobLog.setName(key.getName());
        jobLog.setGroup(key.getGroup());
        Long rowId = jobLogDao.startInsert(jobLog);
        id.set(rowId);
    }

    @Override
    public void jobExecutionVetoed(JobExecutionContext context) {
        Long rowId = id.get();
        if (rowId != null) {
            JobLog jobLog = new JobLog();
            jobLog.setEndTime(new Date());
            jobLog.setId(rowId);
            jobLog.setJobException("任务被拒绝！");
            jobLogDao.endInsert(jobLog);
        }
    }

    @Override
    public void jobWasExecuted(JobExecutionContext context, JobExecutionException jobException) {
        Long rowId = id.get();
        if (rowId != null) {
            JobLog jobLog = new JobLog();
            jobLog.setId(rowId);
            jobLog.setEndTime(new Date());
            if (jobException == null) {
                jobLog.setMark("任务顺利结束");
            } else {
                jobLog.setJobException(jobException.getMessage().substring(0, 100));
            }

            System.out.println(jobLogDao.endInsert(jobLog));
        }
    }

    public void setJobLogDao(JobLogDao jobLogDao) {
        this.jobLogDao = jobLogDao;
    }
}
